package com.gupao.gupaoeduvippattern.javaBase.day02;

import org.dom4j.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class DomService {

    public DomService() {
        // TODO Auto-generated constructor stub
    }
    public static List<Book> getBooks(InputStream inputStream) throws Exception{
        List<Book> list = new ArrayList<Book>();

        //创建一个document解析工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //实例化一个DocumentBuilder对象
        DocumentBuilder builder = factory.newDocumentBuilder();
        //使用DocumentBuilder对象获取一个Document的对象
        Document document = builder.parse(inputStream);
        Element element = document.getDocumentElement();  //获得元素节点
        NodeList nodeList = element.getElementsByTagName("book"); //获取book节点
        for(int i=0; i<nodeList.getLength(); i++){
            Element bookElement = (Element) nodeList.item(i);
            Book book = new Book();  //实例化 Book 对象
            book.setId(Integer.parseInt(bookElement.getAttribute("id")));
            NodeList childNodes = bookElement.getChildNodes();
            for(int j=0; j<childNodes.getLength(); j++){
                if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE){
                    if("name".equals(childNodes.item(j).getNodeName())){
                        book.setName(childNodes.item(j).getFirstChild().getNodeValue());
                    }else if("price".equals(childNodes.item(j).getNodeName())){
                        book.setPrice(Float.parseFloat(childNodes.item(j).getFirstChild().getNodeValue()));
                    }
                }
            }
            list.add(book);
        }
        return list;
    }
    //xml文件的路径
    private static String FilePath = "E:/JavaCode/javaCode/android_dom_xml/book.xml";
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            File file = new File(FilePath);
            InputStream inputStream = new FileInputStream(file);
            List<Book> list = getBooks(inputStream);
            for(Book book:list){
                System.out.println(book.toString());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
